AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
util.PrecacheSound( "Weapon_Gauss.ChargeLoop" )
util.PrecacheSound( "d3_citadel.podarm_move_start" )
util.PrecacheSound( "d3_citadel.podarm_move_stop" )
util.PrecacheSound( "Streetwar.d3_c17_10b_doormove3" )

function ENT:Initialize()
	self.BaseClass.Initialize(self)
	self.detected = false
	self.charging = false
	self.charged = 0
	self.spawnpos = Vector(0,0,0)
	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
	self.Entity:SetSolid( SOLID_VPHYSICS )
    local phys = self.Entity:GetPhysicsObject()
	if (phys:IsValid()) then
		phys:Wake()
	end
	if not (WireAddon == nil) then
		self.WireDebugName = self.PrintName
		self.Inputs = WireLib.CreateInputs(self.Entity, { "Detonate", "Charge" })
		self.Outputs = WireLib.CreateOutputs(self.Entity, { "Chargepercent" })
	end
end

function ENT:ToggleCharge(value)
	if self.charging then
		if not value then
			self:StopSound( "Weapon_Gauss.ChargeLoop" )
			self:EmitSound( "d3_citadel.podarm_move_stop" )
			self.charging = false
		end
	else
		if value then
			if (self.charged >= 100) then
				self:EmitSound( "Streetwar.d3_c17_10b_doormove3" )
			else
				self:EmitSound( "d3_citadel.podarm_move_start" )
				self:EmitSound( "Weapon_Gauss.ChargeLoop" )
				self.charging = true
			end
		end
	end
end

function ENT:TriggerInput(iname, value)
	if (iname == "Detonate") then
		if value > 0 then
			if self.charged >= 100 then
				self:Detonate()
			else
				local effectdata = EffectData()
				effectdata:SetOrigin(self:GetPos())
				effectdata:SetNormal(Vector(0,0,1))
				effectdata:SetScale(1)
				util.Effect("Explosion", effectdata)
				self.Entity:Remove()
			end
		end
	elseif (iname == "Charge") then
		if value > 0 then
			self:ToggleCharge(true)
		else
			self:ToggleCharge(false)
		end
	end
end

function ENT:OnRemove()
	self:StopSound( "Weapon_Gauss.ChargeLoop" )
	self.BaseClass.OnRemove(self)
end

function ENT:Detonate()
	local effectdata = EffectData()
	effectdata:SetOrigin(self:GetPos())
	effectdata:SetNormal(Vector(0,0,1))
	effectdata:SetScale(1)
	util.Effect("bloweruper", effectdata)
	
	
	local orgin_ents = ents.FindInSphere(self:GetPos(),500)
	for k, v in pairs(orgin_ents) do
		if (v:GetClass() == "vein") then
			v:Detected(30)
		end
	end
	self.Entity:Remove()
end

local chargetimer = 0

function ENT:Think()
	if self.charging then
		if (CurTime() > (chargetimer + 0.1)) then
			self.charged = self.charged + 1
			if not (WireAddon == nil) then Wire_TriggerOutput(self.Entity, "Chargepercent", self.charged) end
			if (self.charged == 100) then
				self:EmitSound( "Streetwar.d3_c17_10b_doormove3" )
				self:ToggleCharge(false)
			end
			chargetimer = CurTime()
		end
	end
end

function ENT:AcceptInput(name,activator,caller)

end